﻿using System.Collections.Generic;
using UnityEngine;

//委托类型
public delegate void MsgDelegate(object[] args);

/// <summary>
/// 消息分发
/// </summary>
public class MsgMgr : MonoBehaviour
{
    public static MsgMgr Instance;
      
    //消息列表
    public Dictionary< string, MsgDelegate> msgDic;
     

    public MsgMgr()
    {
        Instance = this;
        msgDic = new Dictionary<string, MsgDelegate>(); 
    } 

    /// <summary>
    /// 添加事件监听 
    /// </summary>
    /// <param name="name"></param>
    /// <param name="cb"></param>
    public void AddListener(string name, MsgDelegate cb)
    { 
        if (!msgDic.ContainsKey(name))
        {
            msgDic.Add(name, cb); 
        }
        else
        {
            msgDic[name] += cb;
        }
    }

    /// <summary>
    /// 添加事件监听 
    /// </summary>
    /// <param name="name"></param>
    /// <param name="cb"></param>
    public void RemoveListener(string name, MsgDelegate cb)
    {
        if (msgDic.ContainsKey(name))
        {
            msgDic[name] -= cb;
        }
        else
        {
            msgDic.Remove(name);
        }
    }

    /// <summary>
    /// 清除所有的监听者
    /// </summary>
    public  void ClearAllListeners()
    {
        msgDic.Clear();
    }

    /// <summary>
    /// 发送消息
    /// </summary>
    /// <param name="name"></param>
    /// <param name="args"></param>
    public void SendMsg(string name, params object[] args)
    {
        MsgDelegate cb;
        if (msgDic.TryGetValue(name, out cb))
        {
            if (cb != null)
            {
                cb(args);
            }
        }
    }
     
}